﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
using AMM.Business;
using AMM.Business.Store;
using AMM.CustomWinControls;
using AMM.Model;
using AMM.Model.PrintModels;
using AMM.Model.Store;
using AMM.UserControls;
using Microsoft.Reporting.WinForms;

namespace AMM.Forms.Store {
    public partial class FrmSuspenseOrder : FrmSuspenseOrderBase {

        private int _pageIndex;
        private SuspenseOrderSearchModel _searchModel;
        private SuspenseOrderProcessor _suspenseOrderProcessor;
        private List<SuspenseOrderViewModel> _suspenseOrderList;

        #region Override

        protected override string FunctionCode {
            get { return "AMM1416"; }
        }

        protected override BaseSearchControl SearchControl {
            get { return new SuspenseOrderSearchControl(); }
        }

        protected override void Add() {
            this.ResetForms();
            this.ShowEditForm("新增", new SuspenseOrder() { ClassStatus = ClassStatus.Added });
            base.Add();
        }

        protected override void Amend() {
            List<SuspenseOrderViewModel> selectedList = this.dgvSuspenseOrderList.GetSelectedRows<SuspenseOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            SuspenseOrder suspenseOrder = this._suspenseOrderProcessor.FetchSuspenseOrderById(selectedList[0].Key);

            suspenseOrder.ClassStatus = ClassStatus.Updated;
            this.ShowEditForm("修改", suspenseOrder);
            base.Amend();
        }

        protected override void Save() {
            base.Save();
        }

        protected override void Delete() {
            List<SuspenseOrderViewModel> selectedList = this.dgvSuspenseOrderList.GetSelectedRows<SuspenseOrderViewModel>();
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._suspenseOrderProcessor.Delete(selectedList.Select(x => x.Key).ToArray());
                this.MDIParent.SetStatusInformation("删除成功");
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                base.Delete();
            });
        }

        protected override void Print() {
            List<SuspenseOrderViewModel> selectedList = this.dgvSuspenseOrderList.GetSelectedRows<SuspenseOrderViewModel>();
            if (selectedList.Count > 1) { this.OnlySelectSingleRecord(); return; }
            if (selectedList.Count == 0) { this.ShouldSelectSingleRecord(); return; }
            this.CreateNewThread(() => {
                string deviceInfo =
                  "<DeviceInfo>" +
                  "  <OutputFormat>EMF</OutputFormat>" +
                  "  <PageWidth>21.5cm</PageWidth>" +
                  "  <PageHeight>13.7cm</PageHeight>" +
                  "  <MarginTop>0cm</MarginTop>" +
                  "  <MarginLeft>0cm</MarginLeft>" +
                  "  <MarginRight>0cm</MarginRight>" +
                  "  <MarginBottom>0cm</MarginBottom>" +
                  "</DeviceInfo>";

                PrintDataSoruceHelper printDataSoruceHelper = new PrintDataSoruceHelper();
                List<PrintSuspenseOrder> printSuspenseOrder = printDataSoruceHelper.FetchPrintSuspenseOrder(selectedList[0].Key);
                List<PrintSuspenseOrderDetails> printSuspenseOrderDetails = printDataSoruceHelper.FetchPrintSuspenseOrderDetails(selectedList[0].Key);

                this.PrintHelperIns = new PrintHelper("SuspenseOrderPrint.rdlc", this.Text, deviceInfo);
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds", printSuspenseOrder));
                this.PrintHelperIns.ReportDataSources.Add(new ReportDataSource("ds1", printSuspenseOrderDetails));
                base.Print();
            }, () => {
                // for hiding
                this.PrintHelperIns.Dispose();
            });
        }

        protected override void Search(object sender, FrmSearch.SearchArgs e) {
            this.CreateNewThread(() => {
                if (e.IsRevert) {
                    this._searchModel = new SuspenseOrderSearchModel();
                }
                else {
                    this._searchModel = (SuspenseOrderSearchModel)e.SearchModel;
                }
            }, () => {
                this.BindSuspenseOrderList();
            });
        }

        #endregion

        public FrmSuspenseOrder() {
            InitializeComponent();

            this.dgvSuspenseOrderList.DataGridViewModelType = typeof(SuspenseOrderViewModel);
            this.dgvSuspenseOrderDetailList.DataGridViewModelType = typeof(SuspenseOrderDetailsViewModel);
        }

        #region Private methods

        private bool frmEdit_Edit(object sender, FrmEdit.EditArgs e) {
            bool resultFlag = false;
            SuspenseOrder suspenseOrder = (SuspenseOrder)e.EditModel;
            if (suspenseOrder.SuspenseOrderDetails.Count == 0) {
                this.ShowError("请添加订单明细记录！");
                return false;
            }
            if (suspenseOrder.SuspenseOrderDetails.Any(x => !string.IsNullOrEmpty(x.ErrMessage))) {
                this.ShowError("请清除明细表错误信息后尝试保存操作！");
                return false;
            }
            this.PreventCancel = true;
            this.CreateNewThread(() => {
                if (suspenseOrder.ClassStatus == ClassStatus.Added) {
                    suspenseOrder.CreatedBy = LoginUserName;                    
                    this._suspenseOrderProcessor.Insert(suspenseOrder);
                }
                else {
                    suspenseOrder.ModifiedBy = LoginUserName;
                    this._suspenseOrderProcessor.Update(suspenseOrder);
                }
                resultFlag = true;
            }, () => {
                this.ResetForms();
                this.PreventCancel = false;
                if (resultFlag) {
                    this.MDIParent.SetStatusInformation("保存成功");
                    this.FormEdit.Close();
                }
            });

            this.Save();
            return true;
        }

        private void ResetForms() {
            this.BindSuspenseOrderList();
            this.BindSuspenseOrderDetailsList(0);
        }

        private void BindSuspenseOrderList() {
            this.CreateNewThread(() => {
                this._suspenseOrderList = this._suspenseOrderProcessor.FetchSuspenseOrderViewModelList(this._searchModel, this._pageIndex);
            }, () => {
                this.dgvSuspenseOrderList.DataSource = new SortableBindingList<SuspenseOrderViewModel>(this._suspenseOrderList);
                this.pceList.Records = this._searchModel.Records;
                this.pceList.DataBind();
            });
        }

        private void BindSuspenseOrderDetailsList(int suspenseId) {
            List<SuspenseOrderDetailsViewModel> detailsList = new List<SuspenseOrderDetailsViewModel>();
            this.CreateNewThread(() => {
                if (suspenseId != 0) {
                    detailsList = this._suspenseOrderProcessor.FetchSuspenseOrderDetailsViewModelList(suspenseId);
                }
            }, () => {
                this.dgvSuspenseOrderDetailList.DataSource = new SortableBindingList<SuspenseOrderDetailsViewModel>(detailsList);
            });
        }

        private void ShowEditForm(string title, SuspenseOrder suspenseOrder) {
            this.CreateNewThread(() => {
                Thread.Sleep(100);
            }, () => {
                SuspenseOrderEditControl editControl = new SuspenseOrderEditControl();
                this.FormEdit = new FrmEdit();
                editControl.BaseEditModel = suspenseOrder;
                editControl.ValidatorForEdit = this.FormEdit.validatorForEdit;
                this.FormEdit.Controls.Add(editControl);
                this.FormEdit.Edit += new FrmEdit.EditEventHandler(frmEdit_Edit);
                this.FormEdit.Text = string.Format("{0}{1}", title, this.Text);
                FrmEntry.LoadAndRunDialog(this.FormEdit);
            });
        }

        #endregion

        private void FrmSuspenseOrder_Load(object sender, EventArgs e) {
            this.CreateNewThread(() => {
                this.PreventCancel = true;
                this._suspenseOrderProcessor = new SuspenseOrderProcessor(this.pceList.PageSize);
                this._searchModel = new SuspenseOrderSearchModel();
                this._pageIndex = 1;
            }, () => {
                this.WindowState = FormWindowState.Maximized;
                this.ResetForms();
                this.PreventCancel = false;
            });
        }

        private void pceList_Paging(object sender, PaginationArgs e) {
            this._pageIndex = e.PageIndex;
            this.BindSuspenseOrderList();
        }

        private void dgvSuspenseOrderList_DoubleClick(object sender, EventArgs e) {
            if (this.dgvSuspenseOrderList.CurrentRow != null) {
                int suspenseId = (int)this.dgvSuspenseOrderList.CurrentRow.Cells["Key"].Value;
                this.BindSuspenseOrderDetailsList(suspenseId);
            }
        }
    }
}
